package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.mapper.SysFlowMarketMapper;
import com.settlement.system.mapper.SysLazyToolUserMapper;
import com.settlement.system.mapper.SysUserFlowMapper;
import com.settlement.system.model.entity.SysFlowMarket;
import com.settlement.system.model.entity.SysLazyToolUser;
import com.settlement.system.model.entity.SysUserFlow;
import com.settlement.system.model.form.SysUserFlowForm;
import com.settlement.system.model.query.SysUserFlowQuery;
import com.settlement.system.model.vo.SysUserFlowImportVo;
import com.settlement.system.model.vo.SysUserFlowVo;
import com.settlement.system.service.SysUserFlowService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户流程表 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-12-28
 */
@Service
@RequiredArgsConstructor
public class SysUserFlowServiceImpl extends ServiceImpl<SysUserFlowMapper, SysUserFlow> implements SysUserFlowService {


    private final SysLazyToolUserMapper sysLazyToolUserMapper;

    private final SysFlowMarketMapper sysFlowMarketMapper;

    @Override
    public Page<SysUserFlowVo> getPage(SysUserFlowQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 查询数据
        Page<SysUserFlow> page = new Page<>(pageNum, pageSize);
        Page<SysUserFlowVo> voPage = new Page<>(pageNum, pageSize);
        Page<SysUserFlow> flowPage = this.baseMapper.getPage(page, queryParams);
        List<SysUserFlowVo> voList = new ArrayList<>();
        BeanUtils.copyProperties(flowPage, voPage, "records");
        if (flowPage.getRecords().size() > 0) {
            List<Long> flowIdList = flowPage.getRecords().stream().map(SysUserFlow::getFlowId).toList();
            List<SysFlowMarket> sysFlowMarkets = sysFlowMarketMapper.selectBatchIds(flowIdList);
            List<Long> userIdList = flowPage.getRecords().stream().map(SysUserFlow::getUserId).toList();
            List<SysLazyToolUser> sysLazyToolUsers = sysLazyToolUserMapper.selectBatchIds(userIdList);
            for (SysUserFlow record : flowPage.getRecords()) {
                SysUserFlowVo vo = new SysUserFlowVo();
                BeanUtils.copyProperties(record, vo);
                sysFlowMarkets.stream().filter(sysFlowMarket -> sysFlowMarket.getId().equals(record.getFlowId())).findFirst().ifPresent(sysFlowMarket -> {
                    vo.setType(sysFlowMarket.getType());
                    vo.setFlowName(sysFlowMarket.getFlowName());
                });
                sysLazyToolUsers.stream().filter(sysLazyToolUser -> sysLazyToolUser.getId().equals(record.getUserId())).findFirst().ifPresent(sysLazyToolUser -> vo.setUserName(sysLazyToolUser.getMobile()));
                voList.add(vo);
            }
        }
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public boolean saveSysUserFlow(SysUserFlowForm sysUserFlowForm) {
        SysUserFlow sysUserFlow = new SysUserFlow();
        BeanUtil.copyProperties(sysUserFlowForm, sysUserFlow);
        sysUserFlow.setCreateTime(null);
        return this.saveOrUpdate(sysUserFlow);
    }

    @Override
    public SysUserFlowForm getSysUserFlowFormData(Long id) {
        SysUserFlow sysUserFlow = this.getById(id);
        SysUserFlowForm sysUserFlowForm = new SysUserFlowForm();
        BeanUtil.copyProperties(sysUserFlow, sysUserFlowForm);
        return sysUserFlowForm;
    }

    @Override
    public boolean deleteSysUserFlow(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
    }

    @Override
    public void importData(List<SysUserFlowImportVo> voList) {
        List<SysUserFlow> sysUserFlowList = new ArrayList<>();
        for (SysUserFlowImportVo importVo : voList) {
            SysUserFlow sysUserFlow = new SysUserFlow();
            BeanUtil.copyProperties(importVo, sysUserFlow);
            sysUserFlowList.add(sysUserFlow);
        }
        this.saveOrUpdateBatch(sysUserFlowList);
    }

    @Override
    public List<SysUserFlowImportVo> findByIds(String idsStr) {
        if (StrUtil.isBlank(idsStr)) {
            return new ArrayList<>();
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysUserFlow> sysUserFlowList = this.getBaseMapper().selectBatchIds(ids);
        List<SysUserFlowImportVo> voList = new ArrayList<>();
        for (SysUserFlow sysUserFlow : sysUserFlowList) {
            SysUserFlowImportVo vo = new SysUserFlowImportVo();
            BeanUtil.copyProperties(sysUserFlow, vo);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public void linkFlow(Long flowId, Long userId) {
        SysUserFlow sysUserFlow = this.baseMapper.selectOne(new LambdaQueryWrapper<SysUserFlow>().eq(SysUserFlow::getFlowId, flowId).eq(SysUserFlow::getUserId, userId));
        SysLazyToolUser sysLazyToolUser = sysLazyToolUserMapper.selectById(userId);
        if (sysUserFlow == null) {
            sysUserFlow = new SysUserFlow();
            sysUserFlow.setFlowId(flowId);
            sysUserFlow.setUserId(userId);
            sysUserFlow.setMobile(sysLazyToolUser.getMobile());
            this.save(sysUserFlow);
        } else {
            throw new RuntimeException("您已经下载过此流程，请勿重复下载");
        }
    }
}
